<template>
  <div class="sales-report">
    <!-- 报表头部统计 -->
    <div class="report-summary">
      <div class="summary-card">
        <div class="summary-title">总计</div>
        <div class="summary-stats">
          <div class="stat-item">
            <span class="stat-label">数量:</span>
            <span class="stat-value">{{ summary.totalQuantity }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">销售金额:</span>
            <span class="stat-value">{{ summary.totalSales.toFixed(2) }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">成本:</span>
            <span class="stat-value">{{ summary.totalCost.toFixed(2) }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">毛利:</span>
            <span class="stat-value">{{ summary.totalProfit.toFixed(2) }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">结算额:</span>
            <span class="stat-value">{{ summary.totalSettlement.toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="report-table-container">
      <div class="table-header">
        <div class="table-title">销售明细报表</div>
        <div class="table-actions">
          <button @click="exportData" class="btn-export">导出数据</button>
          <button @click="printReport" class="btn-print">打印报表</button>
        </div>
      </div>
      
      <div class="table-wrapper">
        <table class="report-table">
          <thead>
            <tr>
              <th>类别</th>
              <th>商品名称</th>
              <th>商品代码</th>
              <th>热销程度</th>
              <th>销售金额</th>
              <th>收货代价</th>
              <th>收货金额</th>
              <th>库位代价</th>
              <th>库位金额</th>
              <th>收银代价</th>
              <th>用位名称</th>
              <th>库存名称</th>
              <th>商品名称</th>
              <th>商品代码</th>
              <th>结算额</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in data" :key="index" :class="{ 'negative-row': item.quantity < 0 }">
              <td>{{ item.category || '-' }}</td>
              <td>{{ item.name || '-' }}</td>
              <td>{{ item.code || '-' }}</td>
              <td class="text-center">{{ item.quantity }}</td>
              <td class="text-right">{{ item.sales.toFixed(2) }}</td>
              <td class="text-right">{{ item.cost.toFixed(2) }}</td>
              <td class="text-right">{{ item.profit.toFixed(2) }}</td>
              <td class="text-right">{{ item.margin.toFixed(2) }}</td>
              <td class="text-right">{{ calculateWarehouseAmount(item).toFixed(2) }}</td>
              <td class="text-right">{{ calculateCashierAmount(item).toFixed(2) }}</td>
              <td>{{ item.location || '-' }}</td>
              <td>{{ item.warehouse || '-' }}</td>
              <td>{{ item.name || '-' }}</td>
              <td>{{ item.code || '-' }}</td>
              <td class="text-right settlement-amount">{{ item.sales.toFixed(2) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页器 -->
      <div class="pagination" v-if="totalPages > 1">
        <button 
          @click="changePage(currentPage - 1)" 
          :disabled="currentPage <= 1"
          class="page-btn"
        >
          上一页
        </button>
        
        <span class="page-info">
          第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
        </span>
        
        <button 
          @click="changePage(currentPage + 1)" 
          :disabled="currentPage >= totalPages"
          class="page-btn"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'

const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  filters: {
    type: Object,
    default: () => ({})
  }
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)

const totalPages = computed(() => {
  return Math.ceil(props.data.length / pageSize.value)
})

// 汇总统计
const summary = computed(() => {
  return props.data.reduce((acc, item) => {
    acc.totalQuantity += item.quantity
    acc.totalSales += item.sales
    acc.totalCost += item.cost
    acc.totalProfit += item.profit
    acc.totalSettlement += item.sales // 结算额等于销售额
    return acc
  }, {
    totalQuantity: 0,
    totalSales: 0,
    totalCost: 0,
    totalProfit: 0,
    totalSettlement: 0
  })
})

// 计算库位金额
const calculateWarehouseAmount = (item) => {
  return item.sales * 0.95 // 示例计算，实际根据业务规则
}

// 计算收银金额
const calculateCashierAmount = (item) => {
  return item.sales * 0.98 // 示例计算，实际根据业务规则
}

// 分页切换
const changePage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 导出数据
const exportData = () => {
  // 创建CSV内容
  const headers = ['类别', '商品名称', '商品代码', '数量', '销售金额', '成本', '毛利', '毛利率']
  const csvContent = [
    headers.join(','),
    ...props.data.map(item => [
      item.category || '',
      item.name || '',
      item.code || '',
      item.quantity,
      item.sales.toFixed(2),
      item.cost.toFixed(2),
      item.profit.toFixed(2),
      item.margin.toFixed(2)
    ].join(','))
  ].join('\n')

  // 创建下载链接
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', `销售报表_${new Date().toISOString().slice(0, 10)}.csv`)
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 打印报表
const printReport = () => {
  window.print()
}
</script>

<style scoped>
.sales-report {
  padding: 0;
}

.report-summary {
  margin-bottom: 20px;
}

.summary-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.summary-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  text-align: center;
}

.summary-stats {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  gap: 15px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 100px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.9;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
}

.report-table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.btn-export, .btn-print {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s ease;
}

.btn-export {
  background: #28a745;
  color: white;
}

.btn-export:hover {
  background: #218838;
}

.btn-print {
  background: #6c757d;
  color: white;
}

.btn-print:hover {
  background: #5a6268;
}

.table-wrapper {
  overflow-x: auto;
  max-height: 600px;
  overflow-y: auto;
}

.report-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

.report-table th {
  background: #f8f9fa;
  padding: 12px 8px;
  text-align: left;
  font-weight: 600;
  color: #495057;
  border-bottom: 2px solid #dee2e6;
  position: sticky;
  top: 0;
  z-index: 10;
  white-space: nowrap;
}

.report-table td {
  padding: 10px 8px;
  border-bottom: 1px solid #e9ecef;
  vertical-align: middle;
}

.report-table tbody tr:hover {
  background: #f8f9fa;
}

.negative-row {
  background: #fff5f5 !important;
  color: #e53e3e;
}

.negative-row:hover {
  background: #fed7d7 !important;
}

.text-center {
  text-align: center;
}

.text-right {
  text-align: right;
}

.settlement-amount {
  font-weight: bold;
  color: #28a745;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  gap: 15px;
  background: #f8f9fa;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid #dee2e6;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-btn:hover:not(:disabled) {
  background: #e9ecef;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #6c757d;
}

/* 打印样式 */
@media print {
  .table-actions, .pagination {
    display: none;
  }
  
  .report-table {
    font-size: 10px;
  }
  
  .summary-card {
    background: #f8f9fa !important;
    color: #333 !important;
    border: 1px solid #dee2e6;
  }
}
</style>